package jiaxa.com.jsbridge.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnDrawListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;

import jiaxa.com.jsbridge.R;
import jiaxa.com.jsbridge.beanNative.NvPdf;
import jiaxa.com.jsbridge.util.ToastUtil;

@ContentView(R.layout.activity_pdf)
public class PdfActivity extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener, OnDrawListener {
    @ViewInject(R.id.pdfView)
    private PDFView pdfView;
    private NvPdf bean;
    private ActionBar actionBar;
    private ProgressDialog progress;
    private String basePath = Environment.getExternalStorageDirectory().toString(); //getAbsolutePath()

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);

        //        Intent intent = getIntent();
        //        String extra = intent.getStringExtra(Constant.CALLMODE.pdf);
        //        bean = new Gson().fromJson(extra, PdfBean.class);

        actionBar = this.getSupportActionBar();
        bean = new NvPdf();
        bean.setName("实现了接收另外一个activity跳转过来同时传递参数pdf地址");
        //        actionBar.setTitle(bean.getName());
        actionBar.setDisplayHomeAsUpEnabled(true);


        initView();
    }

    private void initView() {
        String path = basePath + "/apk/1.pdf";
        File file = new File(path);
        if (!file.exists()) {
            final AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setCancelable(false);
            alert.setMessage("文件不存在，是否下载？");
            alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    downloadPDF();
                }
            });
            alert.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            alert.show();
        } else {
            ToastUtil.show("文件存在了");
            loadingPDF();
        }
    }

    private void loadingPDF() {
        String path = basePath + "/apk/1.pdf";
        File file = new File(path);
        if (file.exists()) {
            pdfView.fromFile(file)
                    .defaultPage(0)         //设置默认显示第1页
                    .onPageChange(this)     //设置翻页监听
                    .onLoad(this)           //设置加载监听
                    .onDraw(this)            //绘图监听
                    .enableSwipe(true)   //是否允许翻页，默认是允许翻
                    .swipeHorizontal(false) //pdf文档翻页是否是垂直翻页，默认是左右滑动翻页
                    // .pages( 2 , 3 , 4 , 5  )  //把2 , 3 , 4 , 5 过滤掉
                    .load();
        }
    }

    private void downloadPDF() {
        progress = new ProgressDialog(this);
        progress.setProgress(0);
        progress.setCancelable(false);
        progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progress.setMessage("下载中，请稍候...");
        progress.setProgressNumberFormat("%1d MB / %2d MB");
        String url = "http://www.gov.cn/zhengce/pdfFile/2017_PDF.pdf";  //url="http://shouji.360tpcdn.com/171113/9190a9cbd111af03f07721d884baf14c/com.gotokeep.keep_9642.apk";
        RequestParams params = new RequestParams(url);
        params.setSaveFilePath(basePath + "/apk/1.pdf");
        x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(File result) {
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.show("下载失败，请检查网络");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                progress.dismiss();
                loadingPDF();
            }

            @Override
            public void onWaiting() {
            }

            @Override
            public void onStarted() {
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                progress.setMax((int) total / (1024 * 1024));
                progress.setProgress((int) current / (1024 * 1024));
                progress.show();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return false;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPageChanged(int page, int pageCount) {

    }

    @Override
    public void loadComplete(int nbPages) {

    }

    @Override
    public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {

    }
}
